<template>
  <div class="payment" v-if="order">
    <title-bar :title="'订单详情'"/>
    <div class="time_down payment_group">
      <countdown v-if="order.status===0" :time="leftTime" @countdownend="countDownEnd">
        <template slot-scope="props">
          剩余付款时间:
          <span class="red">{{ props.minutes }}分{{ props.seconds }}秒</span>
        </template>
      </countdown>
      <span v-else>订单状态：{{statusText}}</span>
      <van-button
        v-if="canCancelOrder"
        class="cancel_btn"
        size="mini"
        type="warning"
        plain
        @click="cancelOrder(order)"
      >取消订单</van-button>
    </div>
    <div v-if="order.status === 0 && user.id === order.mid">
      <div class="pay_way_group">
        <div class="pay_way_title">选择支付方式</div>
        <van-radio-group v-model="payWay">
          <van-cell-group>
            <!-- <van-cell>
              <van-radio name="yu" :disabled="balanceDisable">
                <img src="@/assets/images/balance.png" alt="余额支付" width="30" height="30">
                <span style="margin-left: 3px;font-size: 18px;vertical-align:middle;">余额支付</span>
              </van-radio>
            </van-cell>-->
            <van-cell>
              <van-radio name="wx">
                <img src="@/assets/images/wx_pay.png" alt="微信支付" width="113" height="23">
              </van-radio>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <van-button
        class="pay_submit"
        @click="paySubmit"
        :loading="isSubmit"
        type="primary"
        bottomAction
      >去支付</van-button>
    </div>
    <!-- 订单编号等信息 -->
    <top-user-info class="payment_group" v-if="order" :order="order"/>
    <van-cell-group class="payment_group">
      <van-cell v-for="goods in order.orderProducts" :key="goods.id">
        <order-item :goods="goods" :checkbox="false" :stepper="false">
          <div slot="right-text" style="font-size: 12px;">
            <span>提货时间：{{pickupTime(goods) | dateTimeFormat}}</span>
            <van-button
              v-if="canCancelGoods(order, goods)"
              class="cancel_btn"
              size="mini"
              type="warning"
              plain
              @click="cancelGoods(goods)"
            >单品取消</van-button>
          </div>
        </order-item>
      </van-cell>
      <!-- 赠品信息 -->
      <van-cell v-if="order.giftOrder">
        <template slot="icon">
          <div style="width: 90px;height:90px; background-color:red;">
            <img v-lazy="order.giftOrder.productUrl" class="giftImg">
          </div>
        </template>
        <div style="margin-left: 6px;">
          <div slot="title">
            <span class="give_name">{{order.giftOrder.productName}}</span>
            <br>
            <span class="give">（赠品）</span>
          </div>
          <div slot="right-icon">
            <span>×{{order.giftOrder.total}}</span>
          </div>
        </div>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="payment_group">
      <van-cell title="下单时间">
        <div slot="right-icon" class="order_text">
          <b>{{order.createTime}}</b>
        </div>
      </van-cell>
      <van-cell title="商品总数">
        <div slot="right-icon" class="order_text">
          <b>{{productCount}}</b>
        </div>
      </van-cell>
      <van-cell title="总价格">
        <div slot="right-icon" class="order_text yuan">
          <b>{{order.orderprice.toFixed(2)}}</b>
        </div>
      </van-cell>
      <van-cell title="实付金额">
        <div slot="right-icon" class="order_text yuan">
          <b>{{payprice.toFixed(2)}}</b>
        </div>
      </van-cell>
      <van-cell title="优惠金额">
        <div slot="right-icon" class="order_text">
          <span class="yuan">
            <b>{{discountPrice.toFixed(2)}}</b>
          </span>
        </div>
      </van-cell>
      <!-- <van-cell title="积分抵扣">
				<div slot="right-icon" class="order_text">
					<div>
						<span class="yuan"><b>{{deductPrice.toFixed(2)}}</b></span>
						<van-checkbox v-if="order.status === 0" class="coupon_info" v-model="usePoints" label-position="right">可用积分：{{points}}</van-checkbox>
					</div>
				</div>
      </van-cell>-->
    </van-cell-group>
    <!-- 晒单 -->
    <!-- <van-popup v-model="showShare">
      <img src="@/assets/images/share.png" alt="" class="shareMini">
       <van-icon name="close" class="shareclose" size="25px" color="#fff" @click="shareClose"/>
    </van-popup>-->
  </div>
</template>

<script>
import { RadioGroup, Radio, Checkbox, Popup } from "vant";

import {
  ORDER_GET,
  ORDER_WXPAY,
  ORDER_YUPAY,
  CANCEL_ORDER,
  CANCEL_GOODS
} from "@/api/order";
import topUserInfo from "../top-user-info";
import OrderItem from "../order-item";
import getConfig from "@/vue/mixin/get-config";
import wxConfig from "@/vue/mixin/wx-config";
import orderAction from "@/vue/mixin/order-action";
import ItemEcoupon from "@/vue/components/item-ecoupon/";
import TitleBar from "@/vue/components/title-bar/";
import moment from "moment";

export default {
  name: "payment",
  mixins: [getConfig, wxConfig, orderAction],

  props: {
    payId: {
      type: [String, Number],
      required: true
    }
  },

  data() {
    return {
      isSubmit: false,
      payWay: "wx",
      order: null,
      serverTime: null,
      balance: null,
      points: 0,
      usePoints: false,
      giftMsg: "", //订单详情里面的赠品信息
      share: "" //分享
      // showShare:false
    };
  },

  created() {
    this.getGlobalConfig().then();
    this.wxconfig();
    let vm = this;
    this.wx.error(function(err) {
      vm.$dialog.alert({
        message: "支付授权失败：" + err.errMsg
      });
    });

    let shop = this.getShop();
    this.$reqGet(ORDER_GET, {
      orderId: this.payId,
      shopId: shop.id,
      time: new Date().getTime()
    }).then(res => {
      this.serverTime = res.data.time;
      this.order = res.data.data;
      shop = res.data.shop || shop;
      this.order.shopName = shop.realname;
      this.order.shopMobile = shop.mobile;
      (this.order.shopXiaoqu = shop.tXiaoqu),
        (this.order.shopAddress =
          shop.tProvince +
          shop.tCity +
          shop.tArea +
          shop.tXiaoqu +
          shop.tShopname),
        (this.balance = res.data.balance);
      this.points = res.data.points;

      if (!this.balanceDisable) {
        this.payWay = "yu";
      }
      this.getGlobalShare().then(share => {
        vm.share = share;
        if (this.user.isteam === 3) {
          //团长给会员晒单
          this.wxShare(
            this.replateShare(share.masterOrderShareTitle),
            this.replateShare(share.masterOrderShareDesc),
            this.getUri() +
              this.$route.fullPath.slice(1) +
              "/?isteam=" +
              this.user.isteam, //5.11/?isteam=
            share.masterOrderShareIcon
          );
        } else {
          //会员晒单
          this.wxShare(
            this.replateShare(share.customOrderShareTitle),
            this.replateShare(share.customOrderShareDesc),
            this.getUri() + this.$route.fullPath.slice(1),
            share.customOrderShareIcon
          );
        }
      });
    });
  },
  computed: {
    leftTime() {
      let createTime = moment(this.order.createTime).unix() * 1000;
      let payTime = this.globalConfig
        ? this.globalConfig.autoCloseNoPayOrderMin
        : 5;
      let left = (payTime || 5) * 60 * 1000 - (this.serverTime - createTime);
      return left > 0 ? left : 0;
    },

    productCount() {
      return this.order.orderProducts.reduce(
        (total, product) => (total += product.total),
        0
      );
    },

    statusText() {
      const status = this.order.status;

      if (status === -1) {
        return "已取消";
      } else if (status === 0) {
        return "待付款";
      } else if (status === 1) {
        return "待发货";
      } else if (status === 2) {
        return "已发货";
      } else if (status === 3) {
        return "已收货";
      } else if (status === 4) {
        return "待退款";
      } else if (status === 5) {
        return "售后中";
      } else if (status === 6) {
        return "已完成";
      } else {
        return "处理中";
      }
    },

    payprice() {
      if (this.order.status === 0) {
        return Math.max(
          this.order.orderprice - this.discountPrice - this.deductPrice,
          0
        );
      } else {
        return this.order.payprice;
      }
    },
    discountPrice() {
      return this.order.discountprice;
    },
    pointsTransform() {
      let transform = this.globalConfig
        ? this.globalConfig.exchangeIntegral || 200
        : 200;
      return transform;
    },
    deductPrice() {
      if (this.order.status === 0) {
        if (this.usePoints) {
          return Math.min(
            this.order.orderprice - this.discountPrice,
            this.points / this.pointsTransform
          );
        }

        return 0;
      } else {
        return this.order.deductprice;
      }
    },
    balanceDisable() {
      return true;
      // return this.balance < this.payprice;
    },

    canCancelOrder() {
      return (
        this.user.id === this.order.mid &&
        (this.order.status === 0 || this.order.status === 1)
      );
    }
  },

  methods: {
    shareClose() {
      // this.showShare = false;
    },
    paySubmit() {
      
      const couponId = this.selCoupon ? this.selCoupon.id : null;
      const points = this.usePoints
        ? Math.round(this.deductPrice * this.pointsTransform)
        : null;

      if (this.payWay === "yu" || this.payprice === 0) {
        this.yuPay(couponId, points);
      } else if (this.payWay === "wx") {
        let vm = this;
        this.isWxApp().then(isApp => {
          if (isApp) {
            //小程序内支付
            vm.appPay(couponId, points);
          } else {
            //h5页面支付
            vm.wxPay(couponId, points);
          }
        });
      }
    },

    yuPay(couponId, points) {
      // this.$dialog
      //   .confirm({
      //     message: "余额支付：¥" + this.payprice.toFixed(2),
      //     cancelButtonText: "取消"
      //   }).then(() => {
      //     this.$reqPost(ORDER_YUPAY, {
      //       orderId: this.order.id,
      //       couponId: couponId,
      //       points
      //     }).then(res => {
      //       this.showPayResult('success');
      //     }).catch(() => {
      //       this.showPayResult('fail');
      //     });
      //   }).catch(() => {});
    },

    wxPay(couponId, points) {
      this.$reqPost(ORDER_WXPAY, {
        orderId: this.order.id,
        couponId: couponId,
        points
      }).then(res => {
        let v = this;
        let payReq = res.data.data;
        payReq.timestamp = payReq.timeStamp; //js sdk需要小写时间戳
        payReq.success = function(data) {
          v.showPayResult("success");
        };
        payReq.fail = function(data) {
          v.$dialog.alert({
            message: data.errMsg
          });
          v.showPayResult("fail");
        };

        v.wx.ready(function() {
          //调用相关API
          v.wx.chooseWXPay(payReq);
        });
      });
    },

    appPay(couponId, points) {
      let options =
        "orderid=" +
        this.order.id +
        "&couponid=" +
        (couponId || "") +
        "&points=" +
        (points || "") +
        "&token=" +
        this.$util.getLocalStorage("authToken") +
        "&isteam=" +
        this.user.isteam +
        "&masterOrderShareTitle=" +
        encodeURIComponent(
          this.replateShare(this.share.masterOrderShareTitle)
        ) +
        "&customOrderShareTitle=" +
        encodeURIComponent(
          this.replateShare(this.share.customOrderShareTitle)
        ); 
        
      if (this.user.appOpenid) {
        const url = "/pages/pay/payment?";
        this.wx.miniProgram.navigateTo({
          url: url + options
        });
      } else {
        //5.23 this.user.id 不存在的情况下
        options += "&id=" + this.user.id;
        const url = "/pages/login/auth?";
        this.wx.miniProgram.navigateTo({
          url: url + options
        });
      }
    },

    showPayResult(status) {
      this.$router.push({
        name: "paymentStatus",
        params: {
          status: status
        }
      });
    },
    countDownEnd() {
      this.order.status = -1;
    },

    pickupTime(goods) {
      let pickTime = goods.tihuoday;

      if (!pickTime) {
        if (this.globalConfig) {
          pickTime = this.globalConfig.expectedPickTime;
        }
      }
      const timeend = goods.timeend || goods.createTime;
      return Date.parse(timeend.replace(/-/g, "/")) / 1000 + pickTime * 60;
    },

    replateShare(value) {
      return value
        .replace(/{nickname}/, this.user.nickname)
        .replace(/{sname}/, this.order.sname);
    }
  },

  components: {
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Checkbox.name]: Checkbox,
    [topUserInfo.name]: topUserInfo,
    [OrderItem.name]: OrderItem,
    [ItemEcoupon.name]: ItemEcoupon,
    [TitleBar.name]: TitleBar
  }
};
</script>

<style lang="scss" scoped>
.payment {
  .van-popup {
    background-color: transparent;
    width: 270px;
    transform: translate3d(-50%, -53%, 0);
    -webkit-transform: translate3d(-50%, -53%, 0);
    .shareMini {
      width: 100%;
      height: 100%;
    }
    .shareclose {
      left: 50%;
      transform: translateX(-50%);
      margin-top: 20px;
    }
  }
  .giftImg {
    width: 90px;
    height: 90px;
    margin: auto;
  }
  .give_name {
    box-shadow: border-box;
  }
  .give {
    font-size: 12px;
    color: gray;
  }
}

.payment_group {
  margin-bottom: 10px;
}

.popup_panel {
  width: 100%;
  height: 100%;
  background-color: $bg-color;
}

.pay_way_group {
  margin-bottom: 10px;
  img {
    vertical-align: middle;
  }
}

.time_down {
  background-color: #fffeec;
  padding: 10px 15px;
  margin-top: 50px;
}

.pay_submit {
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 100;
}

.pay_way_title {
  padding: 15px;
  background-color: #fff;
}

.order_text {
  color: $red;
  font-size: 16px;
  text-align: right;
  display: flex;

  > i {
    color: gray;
    margin: 14px 0 0 10px;
  }
}

.yuan {
  ::before {
    content: "¥";
    margin-right: 3px;
    font-size: 8px;
  }
}

.coupon_info {
  color: gray;
  font-size: 10px;
}

.cancel_btn {
  position: relative;
  margin-left: 10px;
}
</style>
